import api from './api';
import { FILE_BASE_URL } from './config';

/**
 * 发布问卷（新建）
 * @param {FormData} formData - 包含title, status, creator, createdAt, file(可选)
 * @returns {Promise<Object>} 返回问卷对象
 */
export async function publishSurvey(formData) {
  console.log('publishSurvey', formData);
  const res = await api.post('/api/surveys/publish', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  });
  if (res.data.status === 0) {
    let data = res.data.data;
    if (typeof data === 'string') {
      try {
        const parsed = JSON.parse(data);
        data = parsed.survey || parsed;
      } catch {
        // 解析失败直接返回原始data
      }
    } else if (data && data.survey) {
      data = data.survey;
    }
    return { success: true, message: res.data.message, data };
  } else {
    return { success: false, message: res.data.message };
  }
}

/**
 * 获取问卷列表
 * @returns {Promise<Array>} 返回问卷数组
 */
export async function getSurveyList() {
  console.log('getSurveyList');
  const res = await api.get('/api/surveys/list');
  if (res.data.status === 0) {
    let list = res.data.data || [];
    list = list.map(item => ({
      ...item,
      filePath: patchFileUrl(item.filePath)
    }));
    return { success: true, list };
  } else {
    return { success: false, message: res.data.message, list: [] };
  }
}

/**
 * 获取单个问卷详情
 * @param {number} id - 问卷ID
 * @returns {Promise<Object>} 返回问卷对象
 */
export async function getSurvey(id) {
  console.log('getSurvey', id);
  const res = await api.get(`/api/surveys/${id}`);
  if (res.data.status === 0) {
    let data = res.data.data;
    if (data && data.filePath) {
      data.filePath = patchFileUrl(data.filePath);
    }
    return { success: true, data };
  } else {
    return { success: false, message: res.data.message };
  }
}

/**
 * 修改问卷
 * @param {FormData} formData - 包含id, title, status, creator, createdAt, file(可选)
 * @returns {Promise<Object>} 
 */
export async function updateSurvey(formData) {
  console.log('updateSurvey', formData);
  const res = await api.put('/api/surveys/update', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  });
  if (res.data.status === 0) {
    return { success: true, message: res.data.message };
  } else {
    return { success: false, message: res.data.message };
  }
}

/**
 * 删除问卷
 * @param {number} id - 问卷ID
 * @returns {Promise<Object>}
 */
export async function deleteSurvey(id) {
  console.log('deleteSurvey', id);
  const res = await api.delete(`/api/surveys/delete/${id}`);
  if (res.data.status === 0) {
    return { success: true, message: res.data.message };
  } else {
    return { success: false, message: res.data.message };
  }
}

/**
 * 根据标题获取问卷详情
 * @param {string} title - 问卷标题
 * @returns {Promise<Object>} 返回问卷数组
 */
export async function getSurveyByTitle(title) {
  console.log('getSurveyByTitle', title);
  const res = await api.get(`/api/surveys/title/${encodeURIComponent(title)}`);
  if (res.data.status === 0) {
    let list = res.data.data || [];
    list = list.map(item => ({
      ...item,
      filePath: patchFileUrl(item.filePath)
    }));
    return { success: true, list };
  } else {
    return { success: false, message: res.data.message, list: [] };
  }
}

function patchFileUrl(filePath) {
  if (!filePath) return '';
  if (filePath.startsWith(FILE_BASE_URL)) return filePath;
  const idx = filePath.indexOf('/111/');
  if (idx !== -1) {
    return FILE_BASE_URL + filePath.slice(idx);
  }
  return filePath.replace('http://127.0.0.1:9000', FILE_BASE_URL);
}
